#include "../include/logClass.h"
//#include <time.h>
#include <fstream>
#include <thread>
#include <iomanip>
#include <ctime>

LogClass::LogClass(): mLogQueue(nullptr), mQuit(false)
{
    strBasePath = "./log/";
    strLogFile = "log.txt";
    mLogQueue = new SyncQueue<Log>(2000);

    std::thread t(&LogClass::runThread, this);
    t.detach();
}

LogClass::~LogClass()
{
    if(mLogQueue)
    {
        delete mLogQueue;
        mLogQueue = nullptr; 
    }
}

std::string LogClass::getTime()
{
    auto now = std::chrono::system_clock::now();
    auto time = std::chrono::system_clock::to_time_t(now);
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;

    std::tm tm_time = *std::localtime(&time);
    
    std::ostringstream oss;
    oss << std::put_time(&tm_time, "%Y-%m-%d %H:%M:%S")
        << "." << std::setw(3) << std::setfill('0') << ms.count();
    
    std::string formatted_time = oss.str();
    
    return formatted_time;
}

void LogClass::writeLog(const std::string msg)
{
    if(mLogQueue && !mLogQueue->isFull())
    {
        Log log;
        log.msg = msg;
        log.stime = getTime();
        mLogQueue->Put(log);
    }
}

void LogClass::runThread()
{
    if(!mLogQueue) return;
    while(!mQuit)
    {
        Log log;
        mLogQueue->Take(log);
        std::ofstream ofs;
        ofs.open(strBasePath + strLogFile, std::ios::app);
        ofs << log.stime << "\t" << log.msg << std::endl;

        ofs.close();
    }
}

void LogClass::setBasePath(const std::string & basePath)
{
    strBasePath = basePath;
}